/**
 * Baijiahulian.com Inc.
 * Copyright (c) 2014-2017 All Rights Reserved.
 */
package com.baijia.javaconfig;

import com.baijia.passport.core.RedisTemplate;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;
import java.net.URISyntaxException;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisPool;

/**
 * @title PassportJavaConfig
 * @desc description
 * @author macrohuang
 * @date Jan 11, 2017
 * @version version
 */
@Configuration
@Slf4j
public class PassportJavaConfig {
    @Bean
    public JedisPool jedisPool(@Value("${redis.host}") String host, @Value("${redis.port:6379}") int port,
        @Value("${redis.password:#{null}}") String password, @Value("${redis.timeout:3000}") int timeout,
        @Value("${redis.maxIdle:30000}") int maxIdle, @Value("${redis.default.db:0}") int db,
        @Value("${redis.max_retry:5}") int maxRetry) throws URISyntaxException {
        
        log.info("Try to init redis");
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setTestOnBorrow(true);
        StringBuilder uri = new StringBuilder("redis://");
        if (StringUtils.isNotBlank(password)) {
            uri.append(":").append(password).append("@");
        }
        uri.append(host).append(":");
        uri.append(port).append("/");
        uri.append(db);
        JedisPool jedisPool = new JedisPool(poolConfig, new URI(uri.toString()));
        RedisTemplate.setJedisPool(jedisPool);
        return jedisPool;
    }
}
